<template>
  <!-- 商家版   货源配置 -->
  <div class="supply-config-page bgf radius app-container">
    <div v-if="retailKey!='zysc'">
      <el-button class="font16" icon="el-icon-back" plain type="primary" @click="close">返回 </el-button>
    </div>
    <div class="" v-loading="loading">
      <el-form :model="ruleForm" ref="ruleForm" label-width="auto" class="demo-ruleForm">
        <div class="subtit" v-if="retailKey!='zysc'">
          <formSubTit :title="'分销网名称'"></formSubTit>
        </div>
        <div v-if="retailKey!='zysc'">
          <h2 v-if="$route.query.urlRelaName">{{retailName}}</h2>
          <div v-else>
          <h2 v-if="supplyList&&supplyList.length">{{retailName}}</h2>
          <el-input v-else style="width:250px" v-model="retailName" placeholder="请输入分销网名称"></el-input>
        </div>
        </div>

        <!-- <div class="subtit" v-if="retailKey!='zysc'">
          <formSubTit :title="'分销网轮播图'"></formSubTit>
        </div>
        <div v-if="retailKey!='zysc'">
          <el-upload :action="uploadImgUrl" :file-list="imgFileList" :show-file-list="true" list-type="picture-card" :limit="5" :on-success="handleUploadSuccess" :multiple="true" :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :headers="headers">
            <i class="el-icon-plus"></i>
          </el-upload>
        </div> -->
        <!-- <div class="subtit" v-if="retailKey!='zysc'">
          <formSubTit :title="'分销网关联店铺链接'" :tip="'当前分销网关联的电商店铺链接，如淘宝店、拼多多店等。'"></formSubTit>
        </div>
        <div v-if="retailKey!='zysc'">
          <el-input style="width:250px;" v-model="otherShopAddress" placeholder="请输入关联店铺链接"></el-input>
          <el-button style="margin-left:10px" v-if="supplyList&&supplyList.length" type="primary" size="small" @click="saveOtherShop">保存</el-button>
        </div> -->
        <div class="subtit">
          <formSubTit :title="'游戏'" :tip="'点击游戏进行配置货源'"></formSubTit>
        </div>
        <div class="game-box">
          <selectBtn :options="{
              valueKey: 'id',
              labelKey: 'name',
              labelKey2: 'count',
              itemWidth: 'auto',
              limitShow: '100',
              itemHeight:'auto',
              fontSize:'14px',
              multiple:false
            }" :selectedArr="ruleForm.gametype" :list-data="gameList" @change="gameChange"></selectBtn>
        </div>
        <div class="subtit">
          <formSubTit :title="'已配置货源'"></formSubTit>
        </div>
        <el-form class="search-form-new" :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="游戏：" prop="status">
            <el-select v-model="queryParams.gametype" filterable placeholder="选择游戏" clearable>
              <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="供货商：" prop="superName">
            <el-input v-model="queryParams.superName" placeholder="请输入供货商" clearable></el-input>
          </el-form-item>
          <el-form-item class="btns">
            <el-button type="primary" icon="el-icon-search" @click="getDetail">搜索</el-button>
          </el-form-item>
        </el-form>
        <div class="table_box">

          <el-table v-if="supplyList&&supplyList.length" stripe border ref="multipleTable" :data="supplyList" style="width: 100%">
            <el-table-column label="游戏" width="150">
              <template slot-scope="scope">{{ scope.row.gameName }}</template>
            </el-table-column>
            <el-table-column label="供货人" width="200">
              <template slot-scope="scope">
                <!-- {{ scope.row.superName }} -->
                <div v-if="allYouzhiMap&&allYouzhiMap[scope.row.superId]">
                  <youzhiName :name="scope.row.superName"></youzhiName>
                </div>
                <div v-else>
                  {{ scope.row.superName }}
                </div>

              </template>
            </el-table-column>
            <el-table-column label="供货折扣">
              <template slot-scope="scope">
                <div >
                  {{ scope.row.supplyRise ||10}}折
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="rrise" label="固定加价" width="100">
              <template slot-scope="scope">
                <div>{{scope.row.gudingjiajia}}元</div>
              </template>
            </el-table-column>
            <el-table-column prop="rrise" label="加价百分比" width="100">
              <template slot-scope="scope">
                <div>{{scope.row.rrise}}%</div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="上架类型" width="100">
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.accountType==3">全部</span>
                  <span v-if="scope.row.accountType==1">手动上架</span>
                  <span v-if="scope.row.accountType==2">api上架</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品类型" width="100">
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.ifself==3">全部</span>
                  <span v-if="scope.row.ifself==1">自营商品</span>
                  <span v-if="scope.row.ifself==2">代售商品</span>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="商品数量" width="130" prop="">
              <template slot-scope="scope">
                <span v-if="scope.row.accountType==3">{{scope.row.cot}}</span>
                <span v-if="scope.row.accountType==1">{{scope.row.ziyingCot}}</span>
                <span v-if="scope.row.accountType==2">{{scope.row.apiCot}}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="联系方式" prop="phonenumber" width="120">
              <template slot-scope="scope">
                <span>
                  {{scope.row.lianxishouji|| scope.row.phonenumber }}
                </span><br/>
                <span v-if="scope.row.lianxiweixin">
                  微信:{{scope.row.lianxiweixin }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="自营商城" width="100" prop="">
              <template slot-scope="scope">
                <span v-if="scope.row.domain" class="link" @click="openShop(scope.row)">
                  点击查看
                </span>
                <!-- <a style="color:#6c5dd3" :href="'http://'+(scope.row.domain&&scope.row.domain.includes(',')?scope.row.domain.split(',')[0]:scope.row.domain)" target="_blank"> 点击查看</a> -->
              </template>
            </el-table-column>
            <el-table-column label="店铺简介" show-overflow-tooltip prop="introduction" min-width="150"></el-table-column>
            <el-table-column label="操作" width="100" prop="">
              <template slot-scope="scope">
                <el-button type="del" @click="delConfig(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-else style="text-align:center;font-size:16px;color:#999;line-height:100px">
            未配置货源，请点击上部游戏进行配置货源！
          </div>
        </div>
        <div class="center">
          <!-- <el-button @click="close()">取消</el-button> -->
          <!-- <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">提交</el-button> -->
        </div>
      </el-form>
    </div>
    <!-- <moreSetting ref="moreSetting" @change="change"></moreSetting> -->
    <supplyconfigDialog ref="supplyconfigDialog" @addSuccess="addSuccess"></supplyconfigDialog>
  </div>
</template>

<script>
import formSubTit from "../../components/formSubTit.vue";
import selectBtn from "../../components/select-btn.vue";
import supplyconfigDialog from "./supplyconfigDialog.vue";
import { getToken } from "@/utils/auth";
import {
  getConfig,
  delConfig,
  updateotherShopAddress,
} from "@/api/info/rprice";
import gameListApi from "@/api/gameConfig/gameList";
export default {
  name: "supplyconfig",
  components: { formSubTit, selectBtn, supplyconfigDialog },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      isEdit: false,
      supplyList: [],
      queryParams: {},
      gameList: [], //游戏列表
      goodsNum: [],
      ruleForm: {
        gametype: [],
        supplyIdAddr: null,
      },
      rules: [],
      supplyMine: "",
      retailKey: "",
      retailName: "",
      otherShopAddress: "",
      isAdd: false,

      uploadImgUrl: "",
      imgFileList: [],
    };
  },
  mounted() {
    // this.getSupplyList();
    // this.getDetail();
    // this.getGameList();
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";

    if(this.$route.query.urlRelaName) {
      this.retailName = this.$route.query.urlRelaName;
    }
  },
  watch: {
    queryData: {
      handler(newVal) {
        if (newVal.retailKey) {
          this.isAdd = false;
          this.retailKey = newVal.retailKey;
          this.queryParams.retailKey = this.retailKey;
          if (this.retailKey == "zysc") {
            this.retailName = "自营商城";
          }
          this.getDetail();
          this.getGameList();
        } else {
          this.isAdd = true;
          this.getGameList();
        }
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    queryData() {
      return this.$route.query;
    },
    allYouzhiMap() {
      return this.$store.getters.allYouzhiMap;
    },
  },
  methods: {
    // 保存三方关联店铺
    saveOtherShop() {
      updateotherShopAddress({
        retailKey: this.retailKey,
        otherShopAddress: this.otherShopAddress,
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success("保存成功！");
        }
      });
    },
    // 打开供货商的自营商城
    openShop(item) {
      if (item.domain && item.domain !== "0") {
        const url =
          "http://" +
          (item.domain && item.domain.includes(",")
            ? item.domain.split(",")[0]
            : item.domain);
        window.open(url);
      } else {
        return this.$message.error("该商家没有自营商城！");
      }
    },
    // 新增货源配置成功
    addSuccess(retailKey) {
      this.retailKey = retailKey;
      this.queryParams.retailKey = this.retailKey;
      this.getDetail();
    },
    // 查询已配置的货源
    getDetail() {
      if (!this.retailKey) {
        return;
      }
      getConfig(this.queryParams)
        .then((res) => {
          this.supplyList = res.data;
          if (res.data && res.data.length) {
            this.retailName = res.data[0].retailName;
            this.otherShopAddress = res.data[0].otherShopAddress;
          }
        })
        .catch((err) => {});
    },
    // 游戏选择变化
    gameChange(val, item) {
      if (!this.retailName) {
        return this.$message.error("请输入分销网名称！");
      }
      let game = { ...item };
      this.$refs.supplyconfigDialog.open(
        game,
        this.retailKey,
        this.retailName,
        this.otherShopAddress
      );
    },
    // 删除一条已配置的数据
    delConfig(row) {
      this.$confirm("确定删除该货源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delConfig(row.id).then((res) => {
            this.$message.success(res.msg);
            this.getDetail();
          });
        })
        .catch(() => {});
    },
    async getGameList() {
      this.loading = true;
      let res = await gameListApi.getGameListByCont();
      this.gameList = res.rows;
      this.loading = false;
    },
    close() {
      window.history.go(-1);
    },
    // 图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (fileList.every((item) => item.status == "success")) {
        let tempArr = this.imgFileList.map((m) => {
          return m.url;
        });
        fileList.forEach((t) => {
          if (
            t.url.indexOf("blob:") > -1 &&
            t.response &&
            t.response.data &&
            t.response.data.filePath
          ) {
            if (!tempArr.includes(t.response.data.filePath)) {
              this.imgFileList.push({
                url: t.response.data.filePath,
                name: "",
              });
            }
            return true;
          }
        });
      }
      this.imgFileList;
      console.log(
        "%c Line:312 🥔 this.imgFileList",
        "color:#2eafb0",
        this.imgFileList
      );
    },
    // 图片删除
    handleRemove(item) {
      const that = this;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === item.url) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.imgFileList;
      console.log(
        "%c Line:322 🍰 this.imgFileList",
        "color:#e41a6a",
        this.imgFileList
      );
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传1张图片");
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm.id = this.info.id;
    },
  },
};
</script>
<style scoped lang="scss">
.supply-config-page {
  padding: 20px;
  .subtit {
    margin: 20px 0;
  }
}
.center {
  text-align: center;
  margin-top: 15px;
}
</style>
